import React, { Component } from 'react'
import { ScrollView, View, Picker, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import DateTabs from '@components/DateTabs/index'
import Field from '@components/Field/index'
import { connect } from "react-redux"
import { chooseGameTime } from '@redux/actions'
import { queyElementYPosition } from '@src/utils/pageUtil'
import dayjs from '@src/utils/dateTimeUtil'

import './index.scss'

class GameTimes extends Component {
  constructor(props) {
    super(props)
    this.state={
      gameList: this.tempData(),
      fieldList: [{
        id: '1',
        name: '1号场地',
        tags: ['人工草地', '5人制', '铁笼式'],
        halfTime: false,
        players: 5,
        size: 'small'
      },{
        id: '2',
        name: '2号场地',
        tags: ['人工草地', '11人制', '铁笼式', '半场选择'],
        halfTime: true,
        players: 11,
        size: 'large'
      },{
        id: '3',
        name: '3号场地',
        tags: ['人工草地', '7人制', '铁笼式'],
        halfTime: false,
        players: 7,
        size: 'medium'
      }],
      fieldMode: [
        {
          key: 'half',
          value: '半场'
        },
        {
          key: 'whole',
          value: '全场'
        }
      ]
    }
    this.statusText = ['组队中', '待开始', '已结束']
  }

  tempData = () =>{
    const list = []
    for(let i = 0; i < 24; i+=2){
      list.push({id: i, date: dayjs().format('YYYY-MM-DD'),start: i+':00', end: i +2 +':00', started: i})
    }
    return list
  }

  /**
   * 获取已创建的活动
   */
  getCreatedGames () {
    const list = []
    for(let i = Math.floor(Math.random() * 12); i < Math.floor(Math.random() * 24); i+=2){
      let status =  Math.floor(Math.random() * 3)  //0 组队中 1 待开始 2 已结束
      let players = Math.floor(Math.random() * 10) + 1
      let progress = ''
      switch(status) {
        case 0:
          progress = `(${players-Math.floor(Math.random() * players)}/${players})`
          break
        case 1:
          progress = `(${players}/${players})`
          break
        case 2:
          progress = `(${players}/${players})`
          break
      }
      list.push({
        id: i, 
        date: dayjs().format('YYYY-MM-DD'),
        start: i+':00', 
        end: i +2 +':00', 
        status:status,
        mode: Math.floor(Math.random() * 2) ? '全场' : '半场',
        progress: progress,
        started: i})
    }
    return list
  }

  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount () { }

  componentDidShow () {
    console.log('选择场次显示')
    this.getGameList()
  }

  getGameList () {
    const { actionType = 0 } = this.props
    let gameList = []
    if(actionType == 1){
      gameList = this.getCreatedGames()
    }else{
      gameList = this.tempData()
    }
    this.setState({ gameList })
  }

  componentDidHide () { }

  /**
   * 日期选择滚动吸顶
   * @param {*} e 
   */
  onPageScroll = (e) =>{
    const { isFixed } = this.state || {}

    queyElementYPosition('#fieldChoose', this)
      .then((v) => {
        if(v.top + v.height < 1 && !isFixed) {
          this.setState({isFixed: true})
        }else if(v.top + v.height> 1 && isFixed){
          this.setState({isFixed: false})
        }
      })
      .catch((e) => console.error('query element y position failed.', e))
  }

  hanldeCall = () =>{
    Taro.showToast({title: '拨打电话'})
  }

  gameClick = (isNew) =>{
    Taro.showToast({title: isNew ? '预定' : '直接进入'})
  }

  /**
   * 日期选择
   */
  dateChange = (value) =>{
    this.getGameList()
    this.setState({date: value.format('YYYY-MM-DD')})
  }

  /**
   * 场地选择
   */
  onFieldChange = (index) =>{
    //更新场地index 查询场地场次

    this.setState({currentFieldIndex: index})
  }

  /**
   * 场次确定跳到发起活动页面
   */
  gameTimeOk = (field, game, mode) =>{
    if(this.props.chooseGameTime){
      //临时测试
      if(this.state.date){
        game.date = this.state.date
      }

      this.props.chooseGameTime(field, game, mode)
    }
    Taro.navigateBack({delta: 2})
  }

  /**
   * 进场或聊天
   * @param {Object} game 活动详情
   * @param {Number} tabIndex 进入的页面 0 阵容 1 聊天室
   */
  gotoGame = (game, tabIndex) =>{
    Taro.navigateTo({url: '../game/index'})
  }

  render () {
    const { gameList = [], isFixed, fieldList = [],
      currentFieldIndex=1, fieldMode = [] } = this.state || {}
    const { currentStore = {}, actionType = 0 } = this.props
    const currentField = fieldList[currentFieldIndex] || {}

    const statusClass = ['build', 'wait', 'over']
    return (
      <ScrollView className='gamesPage' enableFlex scrollY onScroll={this.onPageScroll}>
        <View className='storeInfo'>
          <View className='name'>
            <View>{currentStore.name}</View>
            <View className='verified'>未认证</View>
          </View>
          <View className='addr'>{currentStore.addr}</View>
          <View className='phone' onClick={this.hanldeCall}>电话</View>
          {
            currentStore.tags && <View className='tags'>
              {
                currentStore.tags.map((tag,index) => <View key={index} className='tag'>{tag}</View>)
              }
            </View>
          }
        </View>
        {/* <Image mode='scaleToFill' src='http://47.111.70.141:9021/file/downloadById?fileId=2015953488984967456'></Image> */}
        <View id="fieldChoose" className='field'>
          <View className='title'>选择场次</View>
          <Field value={currentFieldIndex} data={fieldList} onChange={this.onFieldChange}></Field>
          <View className='label'>
            {currentField.name}{
              currentField.tags && 
              currentField.tags.length &&
              <View className='tags'>
                ({currentField.tags.join('/')})
              </View>
            }
          </View>
        </View>
        <DateTabs className={isFixed ? 'fixed' : ''} onChange={this.dateChange}></DateTabs>
        <View className='gameList'>
          {
            gameList.map((game,index) => <View key={index} className='gameItem'>
                <View className='time'>
                  <View className='start'>{game.start}</View>
                  <View className='end'>{game.end}结束</View>
                </View>
                {
                  actionType == 0 ? 
                  <View className='status'>{game.started < 5 ? '已预订': ''}</View>
                  :
                  <View className='status'>
                    <View className='mode'>{game.mode}</View>
                    <View className='progress'>
                      {game.progress}
                      <Text class={statusClass[game.status]}>{this.statusText[game.status]}</Text>
                    </View>
                  </View>
                }
                
                {
                  //预定还是进入活动 这里是临时的效果
                  actionType == 0 && (game.started < 5 ?
                  <View className='btn' onClick={() =>this.gameClick(game.started > 5)}>
                    直接进入
                  </View> :
                  (currentField.halfTime ? 
                  <Picker mode='selector' 
                    range={ fieldMode } rangeKey='value'
                    onChange={({detail}) => this.gameTimeOk(currentField, game, fieldMode[detail.value])}>
                      <View className='btn red'>
                        预定
                      </View>
                  </Picker>
                  :
                  <View className='btn  red' onClick={() =>this.gameTimeOk(currentField,game)}>
                    预定
                  </View>))
                }
                {
                  //是否可进场
                  actionType == 1 &&
                  (game.status == 2 ?
                    <View className='btn blue' onClick={() =>this.gotoGame(game, 1)}>
                      聊天
                    </View> :
                    <View className='btn red' onClick={() =>this.gotoGame(game, 0)}>
                      进场
                    </View>)
                }
              </View>)
          }
        </View>
      </ScrollView>
    )
  }
}

export default connect(({store}) =>({currentStore: store.currentStore, actionType: store.actionType}), {chooseGameTime})(GameTimes)

